﻿using System;

namespace DesignModeConsole.OOPAndPOP.AuthSample
{
    public interface IApiAuthencator
    {
        /// <summary>
        /// 解析url
        /// </summary>
        /// <param name="url"></param>
        void Auth(string url);

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="apiRequest"></param>
        void Auth(ApiRequest apiRequest);
    }

    public class DefaultApiAuthencatorImpl : IApiAuthencator
    {
        private readonly ICredentialStorage _credentialStorage;

        public DefaultApiAuthencatorImpl()
        {
            _credentialStorage = new MysqlCredentialStorage();
        }

        public DefaultApiAuthencatorImpl(ICredentialStorage credentialStorage)
        {
            _credentialStorage = credentialStorage;
        }

        public void Auth(string url)
        {
            var apiRequest = ApiRequest.CreateFormFullUrl(url);
            Auth(apiRequest);
        }

        public void Auth(ApiRequest apiRequest)
        {
            //拿着解析后的数据开始操作
            AuthToken clientAuthToken = new AuthToken(apiRequest.Token, apiRequest.Timestamp);
            if (clientAuthToken.IdExpired())
                throw new AggregateException("token 过期");

            var password = _credentialStorage.GetPasswordByAppId(apiRequest.AppId);
            var serverAuthToken = AuthToken.Create(apiRequest.BaseUrl, apiRequest.AppId, password, apiRequest.Timestamp);
            if (!serverAuthToken.Match(clientAuthToken))
                throw new AggregateException("token验证失败");
        }
    }
}